const app = getApp()
const api = require('../../utils/api')

Page({
  data: {
    type: '', // glucose, bloodPressure, weight
    title: '',
    unit: '',
    timeRange: 'week', // day, week, month
    chartData: [],
    statistics: {
      average: '--',
      max: '--',
      min: '--'
    }
  },

  onLoad(options) {
    const { type } = options
    const titles = {
      glucose: '血糖记录',
      bloodPressure: '血压记录',
      weight: '体重记录'
    }
    const units = {
      glucose: 'mmol/L',
      bloodPressure: 'mmHg',
      weight: 'kg'
    }
    
    this.setData({
      type,
      title: titles[type] || '',
      unit: units[type] || ''
    })

    this.fetchData()
  },

  async fetchData() {
    try {
      const { type, timeRange } = this.data
      const records = await api.health.getRecords({ 
        type,
        timeRange,
        limit: timeRange === 'day' ? 24 : 
               timeRange === 'week' ? 7 : 30
      })

      // 处理数据用于图表显示
      const chartData = this.processChartData(records)
      
      // 计算统计数据
      const statistics = this.calculateStatistics(records)

      this.setData({ chartData, statistics })
    } catch (err) {
      console.error('获取记录失败:', err)
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    }
  },

  processChartData(records) {
    // 根据不同时间范围处理数据
    const { timeRange } = this.data
    if (timeRange === 'day') {
      // 24小时视图
      return records.map(r => ({
        time: r.timestamp,
        value: r.value
      }))
    } else if (timeRange === 'week') {
      // 周视图，每天的平均值
      // ... 处理周数据
    } else {
      // 月视图，每天的平均值
      // ... 处理月数据
    }
  },

  calculateStatistics(records) {
    if (!records.length) return {
      average: '--',
      max: '--',
      min: '--'
    }

    const values = records.map(r => r.value)
    return {
      average: (values.reduce((a, b) => a + b, 0) / values.length).toFixed(1),
      max: Math.max(...values),
      min: Math.min(...values)
    }
  },

  changeTimeRange(e) {
    const timeRange = e.currentTarget.dataset.range
    this.setData({ timeRange }, () => {
      this.fetchData()
    })
  },

  goToRecord() {
    wx.navigateTo({
      url: `/pages/record/record?type=${this.data.type}`
    })
  }
})